package com.android.jmdnstest;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceInfo;
import javax.jmdns.ServiceListener;

public class MainActivity extends AppCompatActivity {
    public WifiManager.MulticastLock lock;
    public static final String TAG = MainActivity.class.getSimpleName();
    private String type = "_raop._tcp.local.";//_airplay._tcp.local.
    public ListView mListView;
    public List<String> mList = null;
    public ArrayAdapter<String> adapter;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        mList = new ArrayList<>();
        adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, mList);
        mListView.setAdapter(adapter);


    }

    private void initView() {
        mListView = (ListView) findViewById(R.id.listview);
        View inflate = View.inflate(this, R.layout.head, null);
        mListView.addHeaderView(inflate);
        mListView.setEmptyView(getLayoutInflater().inflate(R.layout.activity_multicast_demo, null));
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String s = mList.get(i);
                Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        setUp();
    }

    public ServiceInfo serviceInfo;
    public JmDNS jmDNS;
    public ServiceListener listener;
    public WifiManager wifi;

    private void setUp() {
        new Thread(new Runnable() {
            @SuppressLint("WifiManagerLeak")
            @Override
            public void run() {
                wifi = ((WifiManager) getSystemService(Context.WIFI_SERVICE));
                lock = wifi.createMulticastLock(getClass().getSimpleName());
                lock.setReferenceCounted(true);
                try {
                    InetAddress localIpAddress = getLocalIpAddress();
                    String hostName = localIpAddress.getHostName();
                    lock.acquire();
                    jmDNS = JmDNS.create(localIpAddress);
                    listener = new ServiceListener() {
                        @Override
                        public void serviceAdded(ServiceEvent serviceEvent) {
                            jmDNS.requestServiceInfo(serviceEvent.getType(),
                                    serviceEvent.getName(), 1);
                            Log.e(TAG, serviceEvent.toString() + "type" + serviceEvent.getType()
                                    + "dns" + serviceEvent.getDNS());

                        }

                        @Override
                        public void serviceRemoved(ServiceEvent serviceEvent) {
                            Log.d(TAG, "Service removed: " + serviceEvent.getName() + serviceEvent.getInfo().getQualifiedName()
                                    + serviceEvent.getInfo().getPort());

                        }

                        @Override
                        public void serviceResolved(ServiceEvent serviceEvent) {
                            String name = serviceEvent.getName();
                            //Log.d(TAG, "Service Type : " + serviceEvent.getInfo().getType());
                            String hostName1 = serviceEvent.getInfo().getAddress().getHostName();
                            Log.e("IP地址", hostName1 + "    端口号" + serviceEvent.getInfo().getPort() +
                                    "    名称" + name + "   服务类型  " + serviceEvent.getType());

                            String[] split = name.split("@");
                            mList.add(split[1]  + "\n" + hostName1);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    adapter.notifyDataSetChanged();
                                }
                            });

                            if(TextUtils.isEmpty(name)){

                            }
                        }
                    };
                    jmDNS.addServiceListener(type, listener);

                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }
            }
        }).start();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (jmDNS != null) {
            if (listener != null) {
                jmDNS.removeServiceListener(type, listener);
                listener = null;
            }
            jmDNS.unregisterAllServices();
            try {
                jmDNS.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            jmDNS = null;
        }
        lock.release();
    }

    private Map<String, String> getDeviceDetailsMap() {
        HashMap<String, String> info = new HashMap<>();
        info.put("device_name", "my_device_name");
        return info;
    }

    public InetAddress getLocalIpAddress() {
        @SuppressLint("WifiManagerLeak") WifiManager wifiManager = (WifiManager)
                getSystemService(Context.WIFI_SERVICE);
        WifiInfo connectionInfo = wifiManager.getConnectionInfo();
        int ipAddress = connectionInfo.getIpAddress();
        InetAddress address = null;
        try {
            address = InetAddress.getByName(String.format(Locale.ENGLISH, "%d.%d.%d.%d", (ipAddress & 0xff),
                    (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff)));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        return address;
    }

    public void selectClick(View view) {
        startActivity(new Intent(this, MulticastDemoActivity.class));
    }

    private void selectDevice() {
    }
}
